package com.ckcool.api.util;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Component
@Slf4j
public class RestUtilLingXing {

    @Resource
    private ExecuteScriptEngine executeScriptEngine;
    /**
     * 领星接口请求类
     *
     * @param requestType "1"代表获取token，"2"代表其他
     * @param method      请求方式
     * @param params      请求参数
     * @param url         请求地址
     * @param headers     请求头
     * @return
     */
    public Object lingXingRequest(String requestType, String method, Map<String, Object> params, String url, Map<String,Object> headers, Map<String, Object> requestBody) throws Exception {

        //01 验证数据
        if (ObjectUtil.isEmpty(requestType)) {
            Assert.isTrue(false, "是否获取TOKEN标识不能为空");
        }
        if (ObjectUtil.isEmpty(method)) {
            Assert.isTrue(false, "请求方式不能为空");
        }
        if (ObjectUtil.isEmpty(url)) {
            Assert.isTrue(false, "请求地址不能为空");
        }
//		RestTemplate REST_TEMPLATE = new RestTemplate();
        Object result = null;
        //02 发送请求
        if ("1".equals(requestType)) {
            HttpHeaders header = new HttpHeaders();
            header.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> httpEntity = new HttpEntity<String>("", header);
            String path = populateQueryParams(params, url, false);
            //result = getBaseAspect().httpRequest(path, HttpMethod.POST, "", header, Object.class, Constants.Read, StrUtil.EMPTY);
            result = executeScriptEngine.httpRequest(path, HttpMethod.POST, "", header, Object.class);
            //			ResponseEntity<Object> objectResponseEntity = REST_TEMPLATE.postForEntity(s, httpEntity, Object.class);
//			result = objectResponseEntity.getBody();
        } else {
            Map<String, Object> signParam = new HashMap<>();
            signParam.putAll(params);
            if (!CollectionUtils.isEmpty(requestBody)) {
                signParam.putAll(requestBody);
            }
            String sign = LingXingApiSign.sign(signParam, params.get("app_key").toString());
            params.put("sign", sign);
            HttpHeaders header = new HttpHeaders();
            if (ObjectUtil.isNotEmpty(headers)) {
                Iterator<Map.Entry<String, Object>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next().getKey();
                    Object value = iterator.next().getValue();
                    header.set(key, value.toString());
                }
            }
            String path = populateQueryParams(params, url,true);
            if (StrUtil.equalsIgnoreCase(RequestMethodKind.Get.getValue(), method)) {
                params.putAll(requestBody);
                result = executeScriptEngine.httpRequest(path, HttpMethod.GET, "", header, Object.class);
            } else if (StrUtil.equalsIgnoreCase(RequestMethodKind.Post.getValue(), method)) {
                result = executeScriptEngine.httpRequest(path, HttpMethod.POST, JSONObject.toJSONString(requestBody), header, Object.class);
            } else {
                Assert.isTrue(false, "不支持的请求类型");
            }
        }
        try {
            JSONArray jsonToListMap = JsonUtil.getJsonToJsonArray(result);
            return jsonToListMap;
        } catch (Exception e) {
            try {
                JSONObject map = JsonUtil.getJsonToBean(result, JSONObject.class);
                return map;
            } catch (Exception ee) {
                return result;
            }
        }
    }

    static String populateQueryParams(Map<String, Object> request, String purl, boolean isEncode) {
        if (request.isEmpty()) {
            return purl;
        }
        StringBuilder url = new StringBuilder(purl);
        url.append("?");
        for (Map.Entry<String, Object> entry : request.entrySet()) {
            try {
                if (isEncode) {
                    url.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
                } else {
                    url.append(entry.getKey()).append("=").append(String.valueOf(entry.getValue()));
                }
                url.append("&");
            } catch (UnsupportedEncodingException e) {
            }
        }
        if (url.charAt(url.length() - 1) == '&') {
            url.deleteCharAt(url.length() - 1);
        }
        return url.toString();
    }
}
